<template>
  <div>
    <!-- 返利子项目资金池查询 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @resetChange="resetChange" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTable
        ref="table"
        columnsRef="qjhChildrenCapitalPoolQuery"
        :isSelectColumn="false"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :onColumnsChange="columns => (this.columns = columns)"
        :onSyncTableData="syncDataHandle"
        :mergeCellMethod="objectSpanMethod"
      >
        <template slot="controls" slot-scope="props">
          <multiuse-button size="small" type="primary"  :click="exportHandler">导 出</multiuse-button>
        </template>
      </FilterTable>
    </Spin>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { queryList, queryAccountType, exportExcel,exporturl } from '@/api/dealerFinance/RebateManage/ChildrenCapitalPoolQuery';
import { exportExcelFile } from '@/utils/index';
import { getOwnerCode } from '@/assets/js/auth';

export default {
  name: 'ChildrenCapitalPoolQuery',
  mixins: [dictionary],

  data() {
    this.BaseTable = null;
    this.conf = { add: '新增', edit: '编辑', show: '明细' };

    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: { dealerCode: getOwnerCode() },
      formData: {},
      isDealer: false,
      exportLoading: false,
      handleType: '',
      drawerTitle: '',
      spanArr1: [], // 一个空的数组，用于存放每一行记录的合并数
      pos1: 0, // spanArr 的索引
      spanArr2: [], // 一个空的数组，用于存放每一行记录的合并数
      pos2: 0 // spanArr 的索引
    };
  },

  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.getAccountType();
  },
  methods: {
    // 合并
    syncDataHandle(dataList) {
      if (!dataList.length) return;
      // 设定一个数组spanArr/contentSpanArr来存放要合并的格数，同时还要设定一个变量pos/position来记录
      this.spanArr1 = [];
      this.spanArr2 = [];
      for (let i = 0; i < dataList.length; i++) {
        if (i === 0) {
          this.spanArr1.push(1);
          this.pos1 = 0;

          this.spanArr2.push(1);
          this.pos2 = 0;
        } else {
          // 判断当前元素与上一个元素是否相同(第1列)
          if (dataList[i].dealerCode === dataList[i - 1].dealerCode) {
            this.spanArr1[this.pos1] += 1;
            this.spanArr1.push(0);
          } else {
            this.spanArr1.push(1);
            this.pos1 = i;
          }

          if (dataList[i].rebateTypeName === dataList[i - 1].rebateTypeName) {
            this.spanArr2[this.pos2] += 1;
            this.spanArr2.push(0);
          } else {
            this.spanArr2.push(1);
            this.pos2 = i;
          }
        }
      }
    },
    // 处理合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1 || columnIndex === 2 || columnIndex === 3) {
        const _row = this.spanArr1[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      } else if (columnIndex === 4) {
        const _row = this.spanArr2[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },

    // 资金账户类型
    async getAccountType(powerType) {
      const res = (await queryAccountType({ powerType: powerType, fundsType: 1 })).data.map(x => ({ text: x.accountTypeName, value: x.id }));
      this.topFilterList.find(x => x.fieldName == 'accountTypeId').itemList = res;
    },
    // 导出
    async exportHandler() {
        let json = Object.assign({}, { CODE: 'CODE_00000240' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
      // await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
      //   confirmButtonText: '下载',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     this.exportLoading = true;
      //     exportExcel(this.fetchParams)
      //       .then(response => {
      //         exportExcelFile(response.data, '返利子项目资金池查询');
      //         this.exportLoading = false;
      //       })
      //       .catch(err => {
      //         console.log(err);
      //       });
      //   })
      //   .catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消'
      //     });
      //   });
    },
    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    resetChange(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },

    createdFrom() {
      return [
        {
          type: 'SELECT',
          label: '动力形式',
          fieldName: 'powerType',
          placeholder: '请选择',
          itemList: this.createDictList('6008'),
          change: val => {
            if (val) {
              this.topFilterList.map(x => {
                if (x.fieldName == 'accountTypeId') {
                  x.initialValue = '';
                  x.itemList = [];
                }
              });
              this.getAccountType(val);
              return;
            }
            this.topFilterList.map(x => {
              if (x.fieldName == 'accountTypeId') {
                x.initialValue = '';
                x.itemList = [];
              }
            });
            this.getAccountType();
          }
        },
        {
          type: 'SELECT',
          label: '返利账户类型',
          fieldName: 'accountTypeId',
          placeholder: '请选择',
          itemList: []
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '事业部',
          dataIndex: 'deptName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '返利账户类型',
          dataIndex: 'rebateTypeName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '返利项目',
          dataIndex: 'rebateSubprojectsName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '预扣',
        //   dataIndex: 'frozenAmount',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   render: props => {
        //     return (
        //       <el-link type="warning" underline={true} onClick={() => this.overHandle(props.row)}>
        //         {props.row.frozenAmount}
        //       </el-link>
        //     );
        //   }
        // },
        {
          title: '累计入账',
          dataIndex: 'totalInAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '累计出账',
          dataIndex: 'totalOutAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '返利余额',
          dataIndex: 'balanceAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          numberFormat: true
        },
        {
          title: '过期金额',
          dataIndex: 'overdueAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          numberFormat: true
        },
        {
          title: '账户状态',
          dataIndex: 'status', // TODO 1003
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1003'),
          render: props => {
            return <span>{this.createDictText(props.row.status, '1003')}</span>;
          }
        },
        {
          title: '最后更新日期',
          dataIndex: 'updatedAt',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        }
      ];
    }
  }
};
</script>
